//
//  AppDelegate.m
//  悦享
//
//  Created by dllo on 16/3/17.
//  Copyright © 2016年 张洪国. All rights reserved.
//

#import "AppDelegate.h"
#import "LeftSlideViewController.h"
#import "HGLeftViewController.h"
#import "HGMusicTableViewCell.h"
#import "HGMusicPlayCollectionViewCell.h"
#import "SongModel.h"
#import "HGAVPlayerManager.h"
#import "HGMusicUrlHnadel.h"
#import "SongLevelModel.h"
#import "HGMinuTableViewCell.h"
#import "JPUSHService.h"
@interface AppDelegate ()

@property (nonatomic, retain) NSMutableArray *dataArr;
@property (nonatomic, assign) NSInteger index;//记录传过来的index的以确定显示的歌曲
@property (nonatomic, retain) UIView *viewMinu;/**<  菜单view */
@property (nonatomic, assign) BOOL isPlay;//判断是不是在播放，改变button图片

@property (nonatomic, retain) UIButton *playButton;//播放按钮

@property (nonatomic, assign) BOOL isMinu;/**<  判断菜单 */

@property (nonatomic, retain) UITableView *minuTableView;/**<  菜单tableview */
@property (nonatomic, assign) BOOL isDanQuXunHuan;/**<  标记单曲循环状态 */

@property (nonatomic, retain) NSString *url;/**<  小collectionView的网址 */
@property (nonatomic, retain) NSString *type;

@end

@implementation AppDelegate
#warning 注册成功返回DeviceToken
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    NSLog(@"注册成功 ：%@", deviceToken);
    // Required
    //把deviceToken发送给服务器
    [JPUSHService registerDeviceToken:deviceToken];
}

#warning 接收远程通知 当有通知推送过来 手指滑动时

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    
    
    
    //取消推送消息的小圆点
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    NSLog(@"接收到通知：%@", userInfo);
    [JPUSHService handleRemoteNotification:userInfo];
}

#warning 注册远程通知失败时走
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    

    
#pragma mark - 远程推送相关
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
        
        
    }
    
    [JPUSHService setupWithOption:launchOptions appKey:@"332e3c7c494aa34855e1cb64" channel:@"app store" apsForProduction:NO];
    
    
    
    CYViewController *cyVC = [[CYViewController alloc] init];
    
    UINavigationController *cyNav = [[UINavigationController alloc] initWithRootViewController:cyVC];
    
    
    cyNav.tabBarItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemBookmarks tag:1002];
    
    
    HSViewController *hsVC= [[HSViewController alloc] init];
    
    UINavigationController *hsNav = [[UINavigationController alloc] initWithRootViewController:hsVC];
    
    
    hsNav.tabBarItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemFeatured tag:1003];
    
    
    //抽屉
    
    HGLeftViewController *leftVC = [[HGLeftViewController alloc] init];
    
    
    ZHGViewController *zhgVC = [[ZHGViewController alloc] init];
    
    self.leftSlide = [[LeftSlideViewController alloc] initWithLeftView:leftVC andMainView:zhgVC];
    
    self.zhgNav = [[UINavigationController alloc] initWithRootViewController:_leftSlide];
    
    _zhgNav.tabBarItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemHistory tag:1004];
    
    self.tabbarController = [[UITabBarController alloc] init];
    
    _tabbarController.viewControllers = @[cyNav, hsNav, _zhgNav];
    
    self.window.rootViewController = _tabbarController;
    
    
    //修改navBar的颜色
    [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:0.46 green:0.82 blue:0.98 alpha:1]];
    //修改tabbar的颜色
    _tabbarController.tabBar.barTintColor = [UIColor whiteColor];

    
    //创建播放条通知对象
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createTableView) name:@"play" object:nil];
    
    //创建删除播放条的通知对象
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeTableView) name:@"removeTableView" object:nil];
    
    //将网址字符串传过来
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleData:) name:@"chuanzhi" object:nil];
    
    //创建播放状态通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playButtonState:) name:@"isPlay" object:nil];
    
    //创建上一曲通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(lastMusic:) name:@"musicButtonLast" object:nil];
    //创建下一曲通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nextMusic:) name:@"musicButtonNext" object:nil];
    //创建单曲循环通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(danQuXunHuanAction:) name:@"danQuXunHuan" object:nil];
    //创建取消单曲循环通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cancelDanQuXunHuanAction:) name:@"CnadledanQuXunHuan" object:nil];
    
    //创建接受type的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(typeAction:) name:@"type" object:nil];
    /**<  初始化数组 */
    self.dataArr = [NSMutableArray array];
    
    /**<  数据处理  小collection */
    [self handleData];
    
        
    _isDanQuXunHuan = NO;
    _isPlay = YES;
    _isMinu = YES;
    return YES;
}

/**< 接受type的通知  */
- (void)typeAction:(NSNotification *)notification{
    
    self.type = notification.object;
}

/**<  取消单曲循环方法 */
- (void)cancelDanQuXunHuanAction:(NSNotification *)notification{
    _isDanQuXunHuan = NO;
}
/**<  单曲循环方法 */
- (void)danQuXunHuanAction:(NSNotification *)notification{
    
    _isDanQuXunHuan = YES;
    
}

//下一曲
- (void)nextMusic:(NSNotification *)notification{
    
    if (_isDanQuXunHuan == YES) {
        
    }else{
        //判断歌曲当前位置
        if (_index == _dataArr.count-1) {
            _index = 0;
        }else{
            _index++;
        }
        
    }
    
      SongModel *model = _dataArr[_index];
    
    //通知传值
    [[NSNotificationCenter defaultCenter] postNotificationName:@"change" object:model];
    
    //播放对应歌曲
    [self playSongs];
    
    //让collectionview现实对应歌曲
    _playCollection.contentOffset = CGPointMake(_index * (SREEN_WIDTH - 170), 0);
    
    //刷新collectionView
    [_playCollection reloadData];
    
}
//上一曲
- (void)lastMusic:(NSNotification *)notification{
    //判断歌曲当前位置

    if (_isDanQuXunHuan == YES) {
        
    }else{
        if (_index == 0) {
            _index = _dataArr.count - 1;
            NSLog(@"已经是第一首歌");
        }else {
            _index--;
        }
    }
    
    SongModel *model = _dataArr[_index];
    
    //通知传值
    [[NSNotificationCenter defaultCenter] postNotificationName:@"change" object:model];
    
    //播放对应歌曲
    [self playSongs];
    
    //让collectionview现实对应歌曲
    _playCollection.contentOffset = CGPointMake(_index * (SREEN_WIDTH - 170), 0);
    
    //刷新collectionView
    [_playCollection reloadData];
    
}

- (void)createTANchuCaiDan{
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    window.backgroundColor = [UIColor clearColor];
    
    
    self.viewMinu = [[UIView alloc] initWithFrame:CGRectMake(0, SREEN_HEIGHT + 80, SREEN_WIDTH, SREEN_HEIGHT - 265)];
    _viewMinu.backgroundColor = [UIColor whiteColor];
    [window addSubview:_viewMinu];
    
    self.minuTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SREEN_WIDTH, SREEN_HEIGHT - 280) style:UITableViewStylePlain];
    _minuTableView.delegate = self;
    _minuTableView.dataSource = self;
    _minuTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [_viewMinu addSubview:_minuTableView];
    
    [_minuTableView registerClass:[HGMinuTableViewCell class] forCellReuseIdentifier:@"HGMinuTableViewCell"];
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return @"播放列表";
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HGMinuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HGMinuTableViewCell"];
    SongModel *model = _dataArr[indexPath.row];
    
    cell.numberLabel.text = [NSString stringWithFormat:@"%ld", indexPath.row + 1];
    
    cell.model = model;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%ld", indexPath.row);
    
    _index = indexPath.row;
    
    [self playSongs];
    
    _playCollection.contentOffset = CGPointMake(_index * (SREEN_WIDTH -170), 0);
    [_playCollection reloadData];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 30;
}

//修改播放按钮的状态
- (void)playButtonState:(NSNotification *)notification{
    
    if ([notification.object isEqualToString:@"isPlay"]) {
         [_playButton setImage:[UIImage imageNamed:@"iconf111ont-zanting.png"] forState:UIControlStateNormal];
        
        _isPlay = YES;
    }else{
       [_playButton setImage:[UIImage imageNamed:@"iconfont-iconfontbofang.png"] forState:UIControlStateNormal];
        _isPlay = NO;
    }
    
    
    
}
- (void)removeTableView{
    [_playCollection removeFromSuperview];
    [_playView removeFromSuperview];
}

////创建播放条
///创建底层播放的条
- (void)createTableView{
    
    //创建菜单view
    [self createTANchuCaiDan];
    
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    layout.sectionInset = UIEdgeInsetsZero;
    layout.itemSize = CGSizeMake(SREEN_WIDTH - 170, 120);
    
    self.playCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SREEN_WIDTH - 170, 120) collectionViewLayout:layout];
    _playCollection.delegate = self;
    _playCollection.dataSource = self;
    _playCollection.pagingEnabled = YES;
    _playCollection.backgroundColor = [UIColor whiteColor];
    
    _playCollection.contentOffset = CGPointMake(_index * (SREEN_WIDTH - 170), 0);
    
    [_tabbarController.tabBar addSubview:_playCollection];
    
    [_playCollection registerClass:[HGMusicPlayCollectionViewCell class] forCellWithReuseIdentifier:@"HGMusicPlayCollectionViewCell"];
    
    self.playView = [[UIView alloc] initWithFrame:CGRectMake(SREEN_WIDTH - 170, 0, 170, 120)];
    _playView.backgroundColor = [UIColor whiteColor];
    
    [_tabbarController.tabBar addSubview:_playView];
    
    
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _playButton.frame = CGRectMake(20, 0, 50, 50);
    [_playButton setImage:[UIImage imageNamed:@"iconf111ont-zanting.png"] forState:UIControlStateNormal];
    
    [_playButton addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [_playView addSubview:_playButton];
    
    
    UIButton *minuButton = [UIButton buttonWithType:UIButtonTypeCustom];
    minuButton.frame = CGRectMake(80, 0, 50, 50);
    [minuButton setImage:[UIImage imageNamed:@"iconfont-icon12.png"] forState:UIControlStateNormal];
    [minuButton addTarget:self action:@selector(minuButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [_playView addSubview:minuButton];
    
}
//滑动切换歌曲
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    
    if (scrollView == _playCollection) {
        _index = _playCollection.contentOffset.x / (SREEN_WIDTH - 170);
        
        
        
        [self playSongs];
        
    }
}


///播放按钮  暂停按钮
- (void)playButtonAction:(UIButton *)button{
    //开辟一个字符串空间
    NSString *isPlay = [NSString string];
    if (_isPlay == YES) {
        [_playButton setImage:[UIImage imageNamed:@"iconfont-iconfontbofang.png"] forState:UIControlStateNormal];
        [[HGAVPlayerManager shareHGavPlayerManager] pause];
        isPlay = @"isPlay";
    }else{
        [_playButton setImage:[UIImage imageNamed:@"iconf111ont-zanting.png"] forState:UIControlStateNormal];
        [[HGAVPlayerManager shareHGavPlayerManager] play];
        isPlay = @"NoIsPlay";
    }
    //发通知让图片旋转或者停止旋转
    [[NSNotificationCenter defaultCenter] postNotificationName:@"imageAnimation" object:isPlay];
    
    
    _isPlay = !_isPlay;
}
///菜单按钮
- (void)minuButtonAction:(UIButton *)button{
    
    if (_isMinu == YES) {
        [UIView animateWithDuration:0.3 animations:^{
            _viewMinu.frame = CGRectMake(0, SREEN_HEIGHT - (SREEN_HEIGHT - 265)- 45, SREEN_WIDTH, SREEN_HEIGHT - 268);
        }];
        
        [_tabbarController becomeFirstResponder];
        
    }else{
        [UIView animateWithDuration:0.3 animations:^{
            _viewMinu.frame = CGRectMake(0, SREEN_HEIGHT+80, SREEN_WIDTH, SREEN_HEIGHT - 280);
        }];
    }
    
    _isMinu = !_isMinu;
    
}


#pragma mark- tableView代理放啊



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _dataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HGMusicPlayCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HGMusicPlayCollectionViewCell" forIndexPath:indexPath];
    SongModel *model = _dataArr[indexPath.row];
    //标记零行
    if (indexPath.row == 0) {
        model.isRow0 = YES;
    }
    
    cell.model = model;
    
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    SongModel *model = _dataArr[indexPath.row];
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"jumpToVC" object:model];
  
    
}


/**
 *  获取点击的下标
 *
 *  @param notification
 */
- (void)handleData:(NSNotification *)notification{
    
    
    NSLog(@"dddddddd%@", notification.object);
    
    NSString *str = notification.object;
    if ([_type isEqualToString:@"14"]) {
        NSString *index = [str substringFromIndex:@"http://api.favorite.ttpod.com/favorite/song/plaza?random=0&version=0&app=ttpod&v=v8.1.5.2016022418&user_id=0&mid=iPhone5S&f=f320&s=s310&imsi=&hid=&splus=9.2.1&active=1&net=2&openudid=72d26f93c0799c325993cf509c2472027f13fa1d&idfa=EA226D01-40F9-413A-A388-906DF3F490F7&utdid=Vu6ZOeT0fJwDAFqPovwyz9bO&alf=201200&bundle_id=com.ttpod.music&latitude=38.88246122520464&longtitude=121.5395609448811".length];
        NSString *url = [str substringToIndex:@"http://api.favorite.ttpod.com/favorite/song/plaza?random=0&version=0&app=ttpod&v=v8.1.5.2016022418&user_id=0&mid=iPhone5S&f=f320&s=s310&imsi=&hid=&splus=9.2.1&active=1&net=2&openudid=72d26f93c0799c325993cf509c2472027f13fa1d&idfa=EA226D01-40F9-413A-A388-906DF3F490F7&utdid=Vu6ZOeT0fJwDAFqPovwyz9bO&alf=201200&bundle_id=com.ttpod.music&latitude=38.88246122520464&longtitude=121.5395609448811".length];
        
        
        self.index = [index integerValue];
        self.url = url;
    }else{
        
        
        
        NSString *index = [str substringFromIndex:369];
        NSString *url = [str substringToIndex:369];
        
        self.index = [index integerValue];
        self.url = url;
        
        
      
    }
    
    NSLog(@"aaaaaaaaaaaaaaaaaaaaa%ld", _index);
    
    if ([_type isEqualToString:@"14"]) {
        [self handelDataType14];
        /**<  将type重置 */
        _type = @"";
    }else{
        
        /**<  当点击播放列表时的数据处理 */
        [self handleClickData];
        /**<  将type重置 */
        _type = @"";
    }
    
    
    
    
    _playCollection.contentOffset = CGPointMake((SREEN_WIDTH - 170) * _index, 0);
   
}
/**<  当点击播放列表时的数据处理 */
- (void)handleClickData{
    [APPTools GETWithURL:_url par:nil success:^(id responseObject) {
        
        NSLog(@"%@", _url);
        
        NSDictionary *dic = responseObject;
       
        NSArray *songArr = dic[@"songs"];
        
        //移除所有原有的数据
        [_dataArr removeAllObjects];
        
        for (NSDictionary *dic in songArr) {
            SongModel *model = [[SongModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_dataArr addObject:model];
        }
        
        
        
        [_playCollection reloadData];
        [_minuTableView reloadData];
        
        NSLog(@"3339999999999999%ld", _dataArr.count);
        
        
        //播放音乐 （因为数据处理有延迟所以放在这里）
        [self playSongs];
    } filed:^(NSError *error) {
        
    }];

}
/**<  二次点击type14d数据处理 */
- (void)handelDataType14{
    [APPTools GETWithURL:_url par:nil success:^(id responseObject) {
        
        
        NSDictionary *dic = responseObject;
        NSDictionary *dataDic = dic[@"data"];
        NSArray *songArr = dataDic[@"songs"];
        
        //移除所有原有的数据
        [_dataArr removeAllObjects];
        
        for (NSDictionary *dic in songArr) {
            SongModel *model = [[SongModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_dataArr addObject:model];
        }

        
        
        [_playCollection reloadData];
        [_minuTableView reloadData];
        //播放音乐 （因为数据处理有延迟所以放在这里）
        [self playSongs];

        
    } filed:^(NSError *error) {
        
    }];
    

}

//程序第一次运行时默认数据处理
- (void)handleData{
    
  
    
    [APPTools GETWithURL:@"http://api.favorite.ttpod.com/favorite/song/plaza?random=0&version=0&app=ttpod&v=v8.1.5.2016022418&user_id=0&mid=iPhone5S&f=f320&s=s310&imsi=&hid=&splus=9.2.1&active=1&net=2&openudid=72d26f93c0799c325993cf509c2472027f13fa1d&idfa=EA226D01-40F9-413A-A388-906DF3F490F7&utdid=Vu6ZOeT0fJwDAFqPovwyz9bO&alf=201200&bundle_id=com.ttpod.music&latitude=38.88246122520464&longtitude=121.5395609448811" par:nil success:^(id responseObject) {
        
        
        NSDictionary *dic = responseObject;
        NSDictionary *dataDic = dic[@"data"];
        NSArray *songArr = dataDic[@"songs"];
        
        self.dataArr = [SongModel baseModelHandleWithArr:songArr];
        
        
        [_playCollection reloadData];
        [_minuTableView reloadData];
        
        
    } filed:^(NSError *error) {
        
    }];

}
#pragma mark- 控制歌曲播放
- (void)playSongs{
    
    
    
    SongModel *model = _dataArr[_index];
  SongLevelModel *model2  = [model.urlListArr lastObject];
    NSString *urlMusic = model2.url;
   
    
    //播放
    [[HGAVPlayerManager shareHGavPlayerManager] playMusicWithUrl:urlMusic];
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"imageAnimation" object:nil];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    
    [[NSUserDefaults standardUserDefaults] setInteger:_index forKey:@"index"];
    NSLog(@"dddddd$%ld", _index);
}

@end
